package com.zzedu.framework.web.service.impl;

import com.zzedu.common.cache.CacheNameEnum;
import com.zzedu.common.constant.Constants;
import com.zzedu.common.core.domain.entity.SysUser;
import com.zzedu.common.exception.user.UserPasswordNotMatchException;
import com.zzedu.common.exception.user.UserPasswordRetryLimitExceedException;
import com.zzedu.common.utils.MessageUtils;
import com.zzedu.common.utils.SecurityUtils;
import com.zzedu.framework.manager.AsyncManager;
import com.zzedu.framework.manager.factory.AsyncFactory;
import com.zzedu.framework.web.service.SysPasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 登录密码方法
 *
 * @author smarthome
 */
@Component
public class SysPasswordServiceImpl implements SysPasswordService, ApplicationRunner {
    @Autowired
    private CacheManager cacheManager;

    private Cache loginRecordCache;

    @Value(value = "${user.password.maxRetryCount}")
    private String maxRetryCount;


    public void validate(SysUser user, String password) {
        String loginName = user.getUserName();

        AtomicInteger retryCount = loginRecordCache.get(loginName, () -> new AtomicInteger(0));
        if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue()) {
            AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount));
            throw new UserPasswordRetryLimitExceedException(Integer.valueOf(maxRetryCount).intValue());
        }

        if (!matches(user, password)) {
            AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount));
            loginRecordCache.put(loginName, retryCount);
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(loginName);
        }
    }

    public boolean matches(SysUser user, String newPassword) {
//        return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
        return SecurityUtils.matchesPassword(newPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        loginRecordCache.evict(loginName);
    }

    public String encryptPassword(String password) {
        return SecurityUtils.encryptPassword(password);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        loginRecordCache = cacheManager.getCache(CacheNameEnum.LOGINRECORDCACHE.getCode());
    }
}
